//
//  CS_Page_QueryPanelView.m
//  Pods
//
//  Created by 网新中研 on 2017/7/19.
//
//

#import "CS_Page_QueryPanelView.h"
#import <math.h>
#import "FMDB.h"
#import "CS_QueryPanel_ConditionView.h"
#import "CS_QueryPanel_OtherConditionsView.h"

#define MARGIN 10.0
#define WIDTH_LEFT_KEY 60.0
#define WIDTH_RIGHT_BUTTON 35.0
#define WIDTH_INPUT kWindowW - MARGIN
#define WIDTH_QUERY_IAMGE 20.0
#define HEIGHT_CONDITION_BUTTON 35.0

#define QUERY_AREA_HEIGHT 100

#define TAG_QUERY_INPUT_PANNEL_SCROLL_VIEW 23423565
#define KEY_HISTORY_INPUT_TEXT @"KEY_HISTORY_INPUT_TEXT"

@class QueryRecordModel;

@class CS_Item_QueryHistoryView;

typedef void(^HistoryItemClickBlock)(QueryRecordModel *queryRecordModel);

typedef void(^HistoryItemRmoveBlock)(QueryRecordModel *queryRecordModel);


@interface CS_Page_QueryFilterPannelView()

@property (nonatomic, strong) NSArray *queryConditions;

@property (nonatomic, strong) CS_QueryPanel_ConditionView *queryConditionPannelView;

@property (nonatomic, strong) CS_QueryPanel_OtherConditionsView *moreQueryConditionPannelView;

/**
 * CSQueryConditionDisplayMode_InputText型输入条件的分页显示
 */
@property (nonatomic, strong) CS_Page_TabbarContainerView *page_TabbarContainerView;

/**
 * 各种容器视图
 */
@property (nonatomic, strong) NSMutableArray *containerViews;

/**
 * 删选按钮
 */
@property (nonatomic, strong) NSMutableArray *filterButtons;

@property (nonatomic, assign) CGFloat topPrimaryY;


@end

@implementation CS_Page_QueryFilterPannelView

/**
 * 查询条件集合
 */
+(id)page_QueryFilterPannelViewWidthConditions:(NSArray *)queryConditions{
    
    CS_Page_QueryFilterPannelView *queryFilterPannelView = [CS_Page_QueryFilterPannelView new];
    queryFilterPannelView.queryConditions = queryConditions;
    
    return queryFilterPannelView;
}

-(CGFloat)layoutView:(UIView *)superView primaryY:(CGFloat)primaryY{
    
    int defaultCount = 0;
    int inputTextCount = 0;
    int filterLineCount = 0;
    NSMutableArray *filterLineArray = [NSMutableArray new];
    self.topPrimaryY = primaryY;
    
    for (int i = 0; i < self.queryConditions.count; i++) {
        
        CSConditionModel *conditionModel = [self.queryConditions objectAtIndex:i];
        if (conditionModel.queryConditionDisplayMode == CSQueryConditionDisplayMode_Default) {
            defaultCount++;
        }else if (conditionModel.queryConditionDisplayMode == CSQueryConditionDisplayMode_InputText){
            inputTextCount++;
        }else if (conditionModel.queryConditionDisplayMode == CSQueryConditionDisplayMode_ResultFilterLine){
            conditionModel.index = i;
            [filterLineArray addObject:conditionModel];
            filterLineCount++;
        }
        
    }
    
    CGFloat filterHeight = 40;
    CGFloat filterPrimaryY = 0;
    
    if (filterLineCount != 0) {
        CGFloat filterItemWidth = kWindowW/(CGFloat)(filterLineCount + (defaultCount > 0 ? 1 : 0));
        UIView *filterBackgroundView = [UIView new];
        filterBackgroundView.backgroundColor = COLOR_THEME;
        filterBackgroundView.frame = CGRectMake(0, 0, kWindowW, filterHeight);
        
        for (int i = 0; i < filterLineCount; i++) {
            
            CSConditionModel *conditionModel = [filterLineArray objectAtIndex:i];
            
            UIButton *button = [UIButton new];
            [button setTitle:[NSString stringWithFormat:@"%@", conditionModel.placeHolder] forState:UIControlStateNormal];
            button.tag = conditionModel.index;
            [button addTarget:self action:@selector(filterButtonClick:) forControlEvents:UIControlEventTouchUpInside];
            button.frame = CGRectMake(filterItemWidth * i, filterPrimaryY, filterItemWidth, filterHeight);
            button.titleLabel.font = [UIFont systemFontOfSize:FONT_SIZE_2];
            [self styleButton:button image:[CSPageEngine getImageWithKey:KEY_ICON_ARROW_DOWN]];
            [self.filterButtons addObject:button];
            
            
            [filterBackgroundView addSubview:button];
            
            if (i == filterLineCount - 1) {
                if (defaultCount > 0) {
                    
                    UIView *seperatorLineView = [[UIView alloc] init];
                    seperatorLineView.backgroundColor = [UIColor whiteColor];
                    seperatorLineView.frame = CGRectMake(filterItemWidth * (i + 1), filterPrimaryY + 13, 1, 14);
                    [filterBackgroundView addSubview:seperatorLineView];
                    
                    UIButton *button = [UIButton new];
                    [button setTitle:@"更多筛选" forState:UIControlStateNormal];
                    [button addTarget:self action:@selector(openFilterButtonClick:) forControlEvents:UIControlEventTouchUpInside];
                    button.frame = CGRectMake(kWindowW - filterItemWidth, filterPrimaryY, filterItemWidth, filterHeight);
                    button.titleLabel.font = [UIFont systemFontOfSize:FONT_SIZE_2];
                    [self styleButton:button image:[CSPageEngine getImageWithKey:KEY_ICON_ARROW_DOWN]];
                    [filterBackgroundView addSubview:button];
                    [self.filterButtons addObject:button];
                    
                }
            }else{
                
                UIView *seperatorLineView = [[UIView alloc] init];
                seperatorLineView.backgroundColor = [UIColor whiteColor];
                seperatorLineView.frame = CGRectMake(filterItemWidth * (i + 1), filterPrimaryY + 13, 1, 14);
                [filterBackgroundView addSubview:seperatorLineView];
                
            }
            
        }
        
        [self addSubview:filterBackgroundView];
    }else{
        filterHeight = 0;
    }
    
    if (self.page_TabbarContainerView) {

        [self.page_TabbarContainerView layoutView:self primaryY:filterHeight];
        
        //当输入项为空的时候
        if (inputTextCount >=2) {
            filterPrimaryY = 40;
        }

    }
    
    if (inputTextCount > 1) {
        UIView *seperatorLineView = [[UIView alloc] init];
        seperatorLineView.frame = CGRectMake(0, filterHeight + filterPrimaryY - 1, kWindowW, 1);
        seperatorLineView.backgroundColor = COLOR_TOP_SEPERATOR_LINE;
        [self addSubview:seperatorLineView];
    }
    
    self.frame = CGRectMake(0, primaryY, kWindowW, kWindowH - primaryY);
    self.backgroundColor = COLOR_WHITE;
    [superView addSubview:self];
    
    return kWindowH;
}

-(void)styleButton:(UIButton *)button image:(UIImage *)image{
    
    UIImage *imageNew = [self scaleToSize:image size:CGSizeMake(11, 11)];
    [button setImage:imageNew forState:UIControlStateNormal];
    
    CGFloat imageViewWidth = CGRectGetWidth(button.imageView.frame);
    CGFloat labelWidth = CGRectGetWidth(button.titleLabel.frame);
    button.backgroundColor = [UIColor clearColor];
    button.imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth, 0, -labelWidth);
    button.titleEdgeInsets = UIEdgeInsetsMake(0, -imageViewWidth, 0, imageViewWidth);
    button.titleLabel.font = [UIFont boldSystemFontOfSize:14.0];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
}

/**
 * 筛选项为空
 */
-(void)filterButtonClick:(id)sender{
    
    UIButton *button = (UIButton *)sender;
    NSInteger index = button.tag;
    CSConditionModel *conditionModel = [self.queryConditions objectAtIndex:index];
    
    if (self.queryConditionPannelView) {
        
        if (self.queryConditionPannelView.conditionModel == conditionModel
            && self.queryConditionPannelView.superview) {
            [self styleButton:button image:[CSPageEngine getImageWithKey:KEY_ICON_ARROW_DOWN]];
            //隐藏展开的条件
            [self.queryConditionPannelView removeFromSuperview];
            return;
        }
        
        //隐藏之前的
        [self.queryConditionPannelView removeFromSuperview];
        
    }
    
    for (int i = 0; i < self.filterButtons.count; i++) {
        UIButton *filterButton = [self.filterButtons objectAtIndex:i];
        if (filterButton == button) {
            [self styleButton:filterButton image:[CSPageEngine getImageWithKey:KEY_ICON_ARROW_UP]];
        }else{
            [self styleButton:filterButton image:[CSPageEngine getImageWithKey:KEY_ICON_ARROW_DOWN]];
        }
    }
    
    //展开对应条件
    self.queryConditionPannelView = [CS_QueryPanel_ConditionView queryPanel_ConditionView:conditionModel];
    
    __block UIButton *weakButton = button;
    __block CSConditionModel *weakConditionModel = conditionModel;
    
    //当查询条件改变，执行查询处理
    WS(weakSelf);
    self.queryConditionPannelView.onConditionCongiureFinishedHandler = ^(NSString *value, NSString *content) {
        
        if (![weakConditionModel.value isEqualToString:value]) {
            //处理是否必要刷新查询结果
            
            for (int i = 0; i < weakSelf.queryConditions.count; i++) {
                
                CSConditionModel *conditionModel = [weakSelf.queryConditions objectAtIndex:i];
                if (conditionModel.queryConditionDisplayMode == CSQueryConditionDisplayMode_InputText) {
                    conditionModel.isRefreshRequired = YES;
                }
                
            }
        }
        
        weakConditionModel.value = value;
        weakConditionModel.contentValue = content;
        
        if (![weakSelf isNullOrEmpty:value]) {
            [weakButton setTitle:content forState:UIControlStateNormal];
        }else{
            [weakButton setTitle:weakConditionModel.placeHolder forState:UIControlStateNormal];
        }
        
        [weakSelf styleButton:weakButton image:[CSPageEngine getImageWithKey:KEY_ICON_ARROW_DOWN]];
        
        [weakSelf.queryConditionPannelView removeFromSuperview];
        
        if (weakSelf.onConditionChangedHandler) {
            weakSelf.onConditionChangedHandler();
        }
        
    };
    
    self.queryConditionPannelView.onConditionConfigureCancelBlock = ^{
        [weakSelf styleButton:weakButton image:[CSPageEngine getImageWithKey:KEY_ICON_ARROW_DOWN]];
        [weakSelf.queryConditionPannelView removeFromSuperview];
    };
    
    CGFloat primaryY = self.topPrimaryY + 40;
    
    if (self.superview) {
        primaryY = [self.queryConditionPannelView layoutView:self.superview primaryY:primaryY];
    }
    
}

-(void)openFilterButtonClick:(id)sender{
    
    if (!self.superview) {
        return;
    }
    
    UIButton *button = (UIButton *)sender;
    
    if (self.queryConditionPannelView) {
        
        if (self.queryConditionPannelView.superview) {
            
            [self styleButton:button image:[CSPageEngine getImageWithKey:KEY_ICON_ARROW_DOWN]];
            
            //隐藏展开的条件
            [self.queryConditionPannelView removeFromSuperview];
            
            return;
        }
        
        //隐藏之前的
        [self.queryConditionPannelView removeFromSuperview];
        
    }
    
    for (int i = 0; i < self.filterButtons.count; i++) {
        UIButton *filterButton = [self.filterButtons objectAtIndex:i];
        if (filterButton == button) {
            [self styleButton:filterButton image:[CSPageEngine getImageWithKey:KEY_ICON_ARROW_UP]];
        }else{
            [self styleButton:filterButton image:[CSPageEngine getImageWithKey:KEY_ICON_ARROW_DOWN]];
        }
    }
    
    //展开对应条件
    if (self.moreQueryConditionPannelView) {
        [self.superview addSubview:self.moreQueryConditionPannelView];
        self.queryConditionPannelView = self.moreQueryConditionPannelView;
    }else{
        
        self.moreQueryConditionPannelView = [CS_QueryPanel_ConditionView queryPanel_ConditionViewForOther:self.queryConditions];
        WS(weakSelf);
        __weak UIButton *weakButton = button;
        self.moreQueryConditionPannelView.onMoreConditionConfigureFinishedHandler = ^{
            [weakSelf styleButton:weakButton image:[CSPageEngine getImageWithKey:KEY_ICON_ARROW_DOWN]];
            [weakSelf.queryConditionPannelView removeFromSuperview];
        };
        
        self.moreQueryConditionPannelView.onConditionConfigureCancelBlock = ^{
            
            [weakSelf styleButton:weakButton image:[CSPageEngine getImageWithKey:KEY_ICON_ARROW_DOWN]];
            
            [weakSelf.queryConditionPannelView removeFromSuperview];
            
            if (weakSelf.onConditionChangedHandler) {
                weakSelf.onConditionChangedHandler();
            }
        };
        
        self.queryConditionPannelView = self.moreQueryConditionPannelView;
        
        CGFloat primaryY = HEIGHT_NAVIGATIONBAR + 40;
        primaryY = [self.queryConditionPannelView layoutView:self.superview primaryY:primaryY];
        
    }
    
}

-(UIView *)focusedContainerView{
    
    return [self.page_TabbarContainerView getSuperPanelByIndex:self.page_TabbarContainerView.currentIndex];

}

-(NSMutableArray *)filterButtons{
    if (_filterButtons == nil) {
        _filterButtons = [NSMutableArray new];
    }
    return _filterButtons;
}

-(void)clearContainerViews{
    
    for (int i = 0; i <self.page_TabbarContainerView.tabTitles.count; i++) {
        
        UIView *superView = [self.page_TabbarContainerView getSuperPanelByIndex:i];
        REMOVE_SUBVIEWS(superView);
    }
}

-(CS_Page_TabbarContainerView *)page_TabbarContainerView{
    
    if (_page_TabbarContainerView == nil) {
        
        //当查询结果>=2的时候，才对查询结果进行tab分页处理
        if (self.queryConditions) {
            
            NSMutableArray *tabpages = [NSMutableArray new];
            
            for ( int i = 0; i < self.queryConditions.count; i++) {
                CSConditionModel *conditionModel = [self.queryConditions objectAtIndex:i];
                if (conditionModel.queryConditionDisplayMode == CSQueryConditionDisplayMode_InputText) {
                    //如果是输入栏的显示
                    [tabpages addObject:conditionModel.placeHolder];
                    conditionModel.isRefreshRequired = YES;
                }
            }
            
            WS(weakSelf);
            _page_TabbarContainerView = [CS_Page_TabbarContainerView page_TabbarContainerView:tabpages needHeight:kWindowH - HEIGHT_NAVIGATIONBAR onTabIndexChangedHandler:^(NSInteger currentIndex, NSString *currentTitle) {
                
                for (int i = 0; i < self.queryConditions.count; i++) {
                    
                    CSConditionModel *conditionModel = [self.queryConditions objectAtIndex:i];
                    if (conditionModel.queryConditionDisplayMode == CSQueryConditionDisplayMode_InputText) {
                        conditionModel.isFocused = NO;
                        if (i == currentIndex) {
                            conditionModel.isFocused = YES;
                        }
                    }
                }
                
                if (weakSelf.onConditionChangedHandler) {
                    weakSelf.onConditionChangedHandler();
                }
                
            }];
            _page_TabbarContainerView.textColor = COLOR_TEXT_2;
            _page_TabbarContainerView.tablineColor = COLOR_TEXT_2;
            _page_TabbarContainerView.tabBackgroundColor = [UIColor whiteColor];
            _page_TabbarContainerView.normalTitleFont = [UIFont boldSystemFontOfSize:13.0];
            _page_TabbarContainerView.selectedTitleFont = [UIFont boldSystemFontOfSize:13.5];
        }
    }
    
    return _page_TabbarContainerView;
    
}

-(NSMutableArray *)containerViews{
    if (_containerViews == nil) {
        _containerViews = [NSMutableArray new];
    }
    return _containerViews;
}

@end

@implementation CSQueryModuleModel

-(NSString *)modulePlaceHolder{
    
    NSString *placeHolder = @"请输入关键字";
    
    if (self.queryModuleConditions) {
        for (int i = 0; i < self.queryModuleConditions.count; i++) {
            CSConditionModel *conditionModel = [self.queryModuleConditions objectAtIndex:i];
            
            if (conditionModel.isInputTypeProperty) {
                if ([placeHolder isEqualToString:@"请输入关键字"]) {
                    placeHolder = [NSString stringWithFormat:@"请输入%@", conditionModel.placeHolder];
                }else{
                    placeHolder = [NSString stringWithFormat:@"%@，%@", placeHolder, conditionModel.placeHolder];
                }
            }
        }
    }
    
    return placeHolder;
}

@end

@interface QueryRecordModel : NSObject

/**
 * 对应的模块标识
 */
@property (nonatomic, strong) NSString *vc_name;

@property (nonatomic, strong) NSString *query_id;

@property (nonatomic, strong) NSMutableArray *params;

@end

@implementation QueryRecordModel
@end



@interface QueryRecordParamModel : NSObject

@property (nonatomic, strong) NSString *ID;
@property (nonatomic, strong) NSString *record_type;
@property (nonatomic, strong) NSString *param_name;
@property (nonatomic, strong) NSString *param_value;
@property (nonatomic, strong) NSString *param_contentValue;//参数值

@end

@implementation QueryRecordParamModel
@end

@interface QueryRecordManager : NSObject

@property (nonatomic, strong) FMDatabaseQueue *dataBaseQueue;

@property (nonatomic, strong) FMDatabase *dataBase;

-(id)sharedInstance;

//保存记录
-(void)saveRecord:(QueryRecordModel *)queryRecord;

//获取所有记录
-(void)clearRecords:(NSString *)vc_name;

//删除记录
-(void)deleteRecord:(QueryRecordModel *)model;

@end

@implementation QueryRecordManager

static QueryRecordManager *_sharedQueryRecordManager;

-(id)sharedInstance{
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedQueryRecordManager = [QueryRecordManager new];
    });
    
    return _sharedQueryRecordManager;
}

//保存查询记录
-(void)saveRecord:(QueryRecordModel *)queryRecord{
    
    NSString *recordId = [self getQueryRecordId];
    
    queryRecord.query_id = recordId;
    
    __weak QueryRecordModel *weakQueryRecord = queryRecord;
    
    //队列执行
    [self.dataBaseQueue inTransaction:^(FMDatabase * _Nonnull db, BOOL * _Nonnull rollback) {
        
        for (int i = 0; i < weakQueryRecord.params.count; i++) {
            
            QueryRecordParamModel *queryRecordParamModel = [weakQueryRecord.params objectAtIndex:i];
            
            
            
            //执行插入操作
            [db executeUpdate:@"insert into CS_QUERY_RECORD(vc_name, query_id, record_type, param_name, param_value)VALUES(?, ?, ?, ?, ?)", weakQueryRecord.vc_name, weakQueryRecord.query_id, queryRecordParamModel.record_type, queryRecordParamModel.param_name, queryRecordParamModel.param_value];
            
        }
        
    }];
}

//删除记录
-(void)deleteRecord:(QueryRecordModel *)model{
    
    __weak QueryRecordModel *weakModel = model;
    
    [self.dataBaseQueue inTransaction:^(FMDatabase * _Nonnull db, BOOL * _Nonnull rollback) {
        
        [db executeUpdate:@"delete from CS_QUERY_RECORD where query_id = ?", weakModel.query_id];
        
    }];
    
}

-(NSString *)getQueryRecordId{
    
    NSString *randomString = @"";
    
    for (int i = 0; i < 4; i++) {
        
        int randomDigital = arc4random() % 10;
        
        randomString = [NSString stringWithFormat:@"%@%d", randomString, randomDigital];
        
    }
    
    return [NSString stringWithFormat:@"%@%@", randomString, [self getCurrentDateTime:@"yyyyMMddhhmmss"]];
}

-(NSString *)getCurrentDateTime:(NSString *)stringFormat{
    //实例化一个NSDateFormatter对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:stringFormat];
    //用[NSDate date]可以获取系统当前时间
    return [dateFormatter stringFromDate:[NSDate date]];
}

-(void)clearRecords:(NSString *)vc_name{
    
    [self.dataBaseQueue inTransaction:^(FMDatabase * _Nonnull db, BOOL * _Nonnull rollback) {
        
        [db executeUpdate:@"delete from CS_QUERY_RECORD where vc_name=?", vc_name];
        
    }];
    
}

-(NSArray *)getRecords:(NSString *)vc_name{
    
    [self.dataBase open];
    
    FMResultSet *resultSet = [self.dataBase executeQuery:@"select * from CS_QUERY_RECORD where vc_name = ?", vc_name];
    
    QueryRecordModel *queryRecordModel = nil;
    
    NSMutableArray *resultArray = [NSMutableArray new];
    
    while ([resultSet next]) {
        
        NSString *query_id = [resultSet stringForColumn:@"query_id"];
        NSString *param_name = [resultSet stringForColumn:@"param_name"];
        NSString *param_value = [resultSet stringForColumn:@"param_value"];
        NSString *vc_name = [resultSet stringForColumn:@"vc_name"];
        NSString *record_type = [resultSet stringForColumn:@"record_type"];
        NSString *ID = [resultSet stringForColumn:@"ID"];
        
        if (queryRecordModel == nil) {
            queryRecordModel = [QueryRecordModel new];
            queryRecordModel.query_id = query_id;
            queryRecordModel.vc_name = vc_name;
            queryRecordModel.params = [NSMutableArray new];
            [resultArray addObject:queryRecordModel];
        }
        
        if (![query_id isEqualToString:queryRecordModel.query_id]) {
            queryRecordModel = [QueryRecordModel new];
            queryRecordModel.query_id = query_id;
            queryRecordModel.vc_name = vc_name;
            queryRecordModel.params = [NSMutableArray new];
            
            [resultArray addObject:queryRecordModel];
        }
        
        QueryRecordParamModel *queryRecordParamModel = [QueryRecordParamModel new];
        queryRecordParamModel.param_name = param_name;
        queryRecordParamModel.param_value = param_value;
        queryRecordParamModel.record_type = record_type;
        queryRecordParamModel.ID = ID;
        [queryRecordModel.params addObject:queryRecordParamModel];
        
    }
    
    //    if (queryRecordModel != nil) {
    //        [resultArray addObject:queryRecordModel];
    //    }
    
    [self.dataBase close];
    
    return resultArray;
}

-(FMDatabaseQueue *)dataBaseQueue{
    
    if (_dataBaseQueue == nil) {
        
        [self initSqlite];
        
        NSString *filePath = [self getSqliteFilePath];
        
        _dataBaseQueue = [FMDatabaseQueue databaseQueueWithPath:filePath];
        
    }
    return _dataBaseQueue;
}

-(FMDatabase *)dataBase{
    
    if (_dataBase == nil) {
        
        [self initSqlite];
        
        NSString *filePath = [self getSqliteFilePath];
        _dataBase = [FMDatabase databaseWithPath:filePath];
        
    }
    
    return _dataBase;
}

-(void)initSqlite{
    
    NSString *filePath = [self getSqliteFilePath];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    //如果文件不存在
    if (![fileManager fileExistsAtPath:filePath]
        || ![self isTableExist]) {
        
        FMDatabase *dataBase = [FMDatabase databaseWithPath:filePath];
        [dataBase open];
        
        NSString *createQuerySql = @"CREATE TABLE CS_QUERY_RECORD(ID INTEGER PRIMARY KEY AUTOINCREMENT  NOT NULL, vc_name VARCHAR(50), query_id VARCHAR(20),  record_type VARCHAR(10), param_name VARCH AR(100), param_value VARCHAR(255))";
        [dataBase executeUpdate:createQuerySql];
        
        [dataBase close];
        
    }
}

-(NSString *)getSqliteFilePath{
    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [documentsPath stringByAppendingPathComponent:@"queryrecord.sqlit"];
    return filePath;
}

-(BOOL)isTableExist{
    
    FMDatabase *dataBase = [FMDatabase databaseWithPath:[self getSqliteFilePath]];
    [dataBase open];
    
    NSString *existsSql = [NSString stringWithFormat:@"select count(name) as countNum from sqlite_master where type = 'table' and name = '%@'", @"CS_QUERY_RECORD" ];
    
    FMResultSet *rs = [dataBase executeQuery:existsSql];
    
    BOOL isExist = NO;
    
    if ([rs next]) {
        NSInteger count = [rs intForColumn:@"countNum"];
        if (count == 1) {
            NSLog(@"存在");
            isExist = YES;
        }
    }
    
    [dataBase close];
    
    return isExist;
}

@end

@interface CS_Query_RadioView : CSBaseView

@property (nonatomic, strong) CSConditionModel *conditionModel;

@property (nonatomic, strong) NSMutableArray *selectItemButtons;

+(id)query_RadioView:(CSConditionModel *)conditionModel;

-(void)select:(NSString *)code;

@end

@implementation CS_Query_RadioView

+(id)query_RadioView:(CSConditionModel *)conditionModel{
    
    CS_Query_RadioView *query_RadioView = [CS_Query_RadioView new];
    query_RadioView.conditionModel = conditionModel;
    return  query_RadioView;
    
}

-(CGFloat)layoutView:(UIView *)superView primaryY:(CGFloat)primaryY{
    
    if (self.conditionModel == nil) {
        return primaryY;
    }
    
    if (self.conditionModel.type != CSViewType_PageRadioView
        && self.conditionModel.type != CSViewType_PageTextSelectView) {
        return primaryY;
    }
    
    CS_Page_SectionTitleView *sectionTitleView = [CS_Page_SectionTitleView page_SectionTitleView:_conditionModel.name color:COLOR_TEXT_1 image:nil];
    sectionTitleView.isTopSeperatorLineHide = YES;
    CGFloat localPrimaryY = 0;
    localPrimaryY = [sectionTitleView layoutView:self primaryY:localPrimaryY];
    CGFloat primaryX = 0;
    
    for (int i = 0; i < self.conditionModel.selectItems.count; i++) {
        
        id model = [self.conditionModel.selectItems objectAtIndex:i];
        
        NSString *buttonTitle = @"";
        
        if ([model isKindOfClass:[NSString class]]) {
            
            buttonTitle = model;
            
        }else if([model isKindOfClass:[CSSelectableModel class]]){
            
            buttonTitle = ((CSSelectableModel *)model).content;
            
        }
        
        UIButton *conditionButton = [self getConditionButton:buttonTitle];
        
        if (conditionButton.frame.size.width + primaryX + MARGIN > kWindowW - 2 *CELL_EDIT_RIGHT_MARGIN) {
            
            localPrimaryY += HEIGHT_CONDITION_BUTTON + MARGIN;
            primaryX = 0;
            
        }
        
        conditionButton.frame = CGRectMake(primaryX + CELL_EDIT_RIGHT_MARGIN, localPrimaryY, conditionButton.frame.size.width, conditionButton.frame.size.height);
        [self addSubview:conditionButton];
        primaryX += conditionButton.frame.size.width + MARGIN;
        
        [self.selectItemButtons addObject:conditionButton];
        
    }
    
    localPrimaryY += HEIGHT_CONDITION_BUTTON + MARGIN + 5;
    
    self.frame = CGRectMake(0, primaryY, kWindowW, localPrimaryY);
    [superView addSubview:self];
    
    return primaryY + localPrimaryY;
}


-(UIButton *)getConditionButton:(NSString *)conditionButton{
    
    UIButton *button = [UIButton new];
    [button setTitle:conditionButton forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:14.0];
    button.titleLabel.textColor = COLOR_TEXT_3;
    button.layer.borderColor = COLOR_TOP_SEPERATOR_LINE.CGColor;
    button.layer.borderWidth = 1.0;
    [button setTitleColor:COLOR_TEXT_1 forState:UIControlStateNormal];
    button.frame = CGRectMake(0, 0, 0, HEIGHT_CONDITION_BUTTON);
    [button sizeToFit];
    
    button.frame = CGRectMake(0, 0, button.frame.size.width + 20, HEIGHT_CONDITION_BUTTON);
    [button addTarget:self action:@selector(conditionSelectClick:) forControlEvents:UIControlEventTouchUpInside];
    
    return button;
}

-(void)select:(NSString *)code{
    
    for (int i = 0; i < self.conditionModel.selectItems.count; i++) {
        CSSelectableModel *selectableModel = [self.conditionModel.selectItems objectAtIndex:i];
        
        //如果两种相同的话
        if ([code isEqualToString:selectableModel.code]) {
            
            selectableModel.isSelected = NO;
            [self doSelect:selectableModel];
            
            break;
        }
    }
    
}

//选中处理
-(void)doSelect:(CSSelectableModel*)selectedModel{
    
    for (int i = 0; i < self.selectItemButtons.count; i++) {
        
        CSSelectableModel *model = [self.conditionModel.selectItems objectAtIndex:i];
        
        UIButton *button = [self.selectItemButtons objectAtIndex:i];
        
        if ([model.code isEqualToString:selectedModel.code]
            &&selectedModel.isSelected == NO) {
            
            UIColor *color_Selected = COLOR_THEME;
            [button setTitleColor:color_Selected forState:UIControlStateNormal];
            button.layer.borderColor = color_Selected.CGColor;
            button.layer.borderWidth = 1.0;
            model.isSelected = YES;
            
            self.value = model.code;
            self.conditionModel.value = model.code;
            
        }else{
            
            [button setTitleColor:COLOR_TEXT_1 forState:UIControlStateNormal];
            button.layer.borderColor = COLOR_TOP_SEPERATOR_LINE.CGColor;
            button.layer.borderWidth = 1.0;
            model.isSelected = NO;
            
        }
    }
}

-(void)conditionSelectClick:(id)sender{
    
    for (int i = 0; i < self.selectItemButtons.count; i++) {
        
        UIButton *button = [self.selectItemButtons objectAtIndex:i];
        
        if (button == sender) {
            
            [self doSelect:[self.conditionModel.selectItems objectAtIndex:i]];
        }
        
    }
}

-(NSMutableArray *)selectItemButtons{
    if (_selectItemButtons == nil) {
        _selectItemButtons = [NSMutableArray new];
    }
    return _selectItemButtons;
}

@end

@interface CS_Item_QueryHistoryView : CSBaseView

@property (nonatomic, strong) UIImageView *leftImage;
@property (nonatomic, strong) UILabel *contentLabel;
@property (nonatomic, strong) UIButton *removeButton;
@property (nonatomic, strong) UIButton *clickButton;
@property (nonatomic, strong) UIView *seperateLineView;

@property (nonatomic, copy) HistoryItemClickBlock clickHandler;
@property (nonatomic, copy) HistoryItemRmoveBlock removeHandler;
@property (nonatomic, strong) NSString *contentString;
@property (nonatomic, strong) QueryRecordModel *recordModel;

@end

@implementation CS_Item_QueryHistoryView

+(id)item_QueryHistoryView:(NSString *)contentString selectClick:(HistoryItemClickBlock)clickHandler remove:(HistoryItemRmoveBlock)removeHandler{
    CS_Item_QueryHistoryView *item_QueryHistoryView = [CS_Item_QueryHistoryView new];
    item_QueryHistoryView.contentString = contentString;
    item_QueryHistoryView.clickHandler = clickHandler;
    item_QueryHistoryView.removeHandler = removeHandler;
    return item_QueryHistoryView;
}

+(id)item_QueryHistoryViewWithRecordModel:(QueryRecordModel *)queryRecordModel selectClick:(HistoryItemClickBlock)clickHandler remove:(HistoryItemRmoveBlock)removeHandler{
    CS_Item_QueryHistoryView *item_QueryHistoryView = [CS_Item_QueryHistoryView new];
    item_QueryHistoryView.recordModel = queryRecordModel;
    item_QueryHistoryView.clickHandler = clickHandler;
    item_QueryHistoryView.removeHandler = removeHandler;
    return item_QueryHistoryView;
}

-(CGFloat)layoutView:(UIView *)superView primaryY:(CGFloat)primaryY{
    
    //左侧图标
    self.leftImage.frame = CGRectMake(10, 5, 20, 20);
    [self addSubview:self.leftImage];
    
    //中间文字
    self.contentLabel.frame = CGRectMake(35, 0, kWindowW - 35 - 35, 30);
    [self addSubview:self.contentLabel];
    
    //右边按钮
    self.removeButton.frame = CGRectMake(kWindowW - 35, 0, 20, 20);
    
    UIImage *removeImage = [CSPageEngine getImageWithKey:KEY_ICON_REMOVE];
    if (removeImage == nil) {
        removeImage = [UIImage imageNamed:@"remove"];
    }
    
    UIImageView *imageView = [[UIImageView alloc] initWithImage:removeImage];
    imageView.frame = CGRectMake(kWindowW - 35, 10, 10, 10);
    [self addSubview:imageView];
    [self addSubview:self.removeButton];
    
    //点击按钮
    self.clickButton.frame = CGRectMake(0, 0, kWindowW - 35, 30);
    [self addSubview:self.clickButton];
    
    //分割线
    self.frame = CGRectMake(0, primaryY, kWindowW, 30);
    [superView addSubview:self];
    
    return primaryY + 40;
}

-(void)selectClick{
    if (self.clickHandler) {
        self.clickHandler(self.recordModel);
    }
}

-(void)removeClick{
    if (self.removeHandler) {
        self.removeHandler(self.recordModel);
    }
}

-(UIImageView *)leftImage{
    if (_leftImage == nil) {
        UIImage *historyImage = [CSPageEngine getImageWithKey:KEY_ICON_HISTORY];
        if (historyImage == nil) {
            historyImage = [UIImage imageNamed:@"history"];
        }
        _leftImage = [[UIImageView alloc] initWithImage:historyImage];
    }
    return _leftImage;
}

-(UILabel *)contentLabel{
    if (_contentLabel == nil) {
        _contentLabel = [UILabel new];
        _contentLabel.font = [UIFont systemFontOfSize:15.0];
        _contentLabel.textColor = COLOR_TEXT_2;
        _contentLabel.text = self.contentString;
        
        NSString *contentString = @"";
        
        if (self.recordModel) {
            
            for (int i = 0; i < self.recordModel.params.count; i++) {
                
                QueryRecordParamModel *paramModel = [self.recordModel.params objectAtIndex:i];
                
                if ([paramModel.record_type integerValue] == CSViewType_PageTextFieldView
                    ||[paramModel.param_name isEqualToString:KEY_HISTORY_INPUT_TEXT]) {
                    
                    contentString = [NSString stringWithFormat:@"%@ %@", paramModel.param_value, contentString];
                    
                }
            }
            
            _contentLabel.text = contentString;
            
        }
    }
    return _contentLabel;
}

-(UIButton *)removeButton{
    if (_removeButton == nil) {
        _removeButton = [[UIButton alloc] init];
        [_removeButton addTarget:self action:@selector(removeClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _removeButton;
}

-(UIButton *)clickButton{
    if (_clickButton == nil) {
        _clickButton = [[UIButton alloc] init];
        [_clickButton addTarget:self action:@selector(selectClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _clickButton;
}

-(UIView *)seperateLineView{
    if (_seperateLineView == nil) {
        _seperateLineView = [[UIView alloc] init];
    }
    return _seperateLineView;
}

@end

@implementation CSConditionModel

-(void)setSelectItems:(NSArray *)selectItems{
    
    if (selectItems == nil) {
        _selectItems = selectItems;
        return;
    }
    
    NSMutableArray *mutalbeArray = [NSMutableArray new];
    
    for (int i = 0; i < selectItems.count; i++) {
        
        id selectItem = [selectItems objectAtIndex:i];
        
        if ([selectItem isKindOfClass:[NSString class]]) {
            
            CSSelectableModel *selectableModel = [CSSelectableModel new];
            
            selectableModel.name = selectItem;
            selectableModel.content = selectItem;
            selectableModel.code = [NSString stringWithFormat:@"%d", i];
            
            [mutalbeArray addObject:selectableModel];
            
        }else{
            
            [mutalbeArray addObject:selectItem];
            
        }
    }
    
    _selectItems = mutalbeArray;
    
}

@end


@interface CS_Page_QueryPanelView()<UIScrollViewDelegate, UITextFieldDelegate>

@property (nonatomic, strong) UIView *queryTopBackView;

@property (nonatomic, strong) UIView *queryConditionSwitchBackView;

@property (nonatomic, strong) UIView *queryConditionBackView;

@property (nonatomic, strong) UIView *queryHistoryBackView;


/**************************顶部查询栏**************************/

@property (nonatomic, strong) UILabel *titlLabel;
@property (nonatomic, strong) UIView *inputBackgroundView;
@property (nonatomic, strong) UITextField *queryInputTextField;
@property (nonatomic, strong) UIButton *queryLeftButton;
@property (nonatomic, strong) UIButton *queryRightButton;
@property (nonatomic, strong) UIButton *backButton;

/**
 * 查询按钮
 */
@property (nonatomic, strong) UIImageView *queryIconImageView;

/**************************顶部查询栏:变幻关键字**************************/
@property (nonatomic, strong) UIScrollView *scrollView;

@property (nonatomic, assign) CGFloat heightConditionArea;
@property (nonatomic, assign) CGFloat focusDeviation;//焦点位置的偏移量
@property (nonatomic, strong) CSConditionModel *focusModel;
@property (nonatomic, strong) UIView *switchLine;

/**************************搜索条件**************************/
@property (nonatomic, strong) CSConditionModel *selectConditionModel;

@property (nonatomic, strong) UILabel *queryTitleLabel;

@property (nonatomic, strong) UIView *seperateLine;

/***************************分类方式***************************/
@property (nonatomic, strong) UIView *categoryTypeBackgroundView;
@property (nonatomic, strong) CS_Page_SectionTitleView *categoryType_CS_Page_SectionTitleView;
@property (nonatomic, strong) NSMutableArray *categoryButtonArray;

/**************************历史记录****************************/
@property (nonatomic, strong) UIView *historyBackgroundView;
@property (nonatomic, strong) CS_Page_SectionTitleView *history_CS_Page_SectionTitleView;
@property (nonatomic, strong) UIButton *clearHistoryButton;
@property (nonatomic, strong) UIScrollView *historyScrollView;

@property (nonatomic, strong) UIScrollView *expandQueryScrollView;

/**************************历史记录****************************/
@property (nonatomic, strong) CS_Page_TabbarContainerView *module_CS_Page_TabbarContainerView;

/**
 * 搜索记录持久化管理对象
 */
@property (nonatomic, strong) QueryRecordManager *queryRecordManager;

/**
 * 查询记录
 */
@property (nonatomic, strong) NSArray *queryRecords;

@property (nonatomic, assign) BOOL isSwithBarVisible;

///**
// * 查询结果显示视图
// */
//@property (nonatomic, strong) UIView *queryResultDisplayPannelView;

/**
 * 查询过滤条件
 */
@property (nonatomic, strong) CS_Page_QueryFilterPannelView *queryFilterPannelView;

/**
 * 搜索关键字字符串
 */
@property (nonatomic, strong) NSString *queryKeyString;

/**
 * 顶部导航条高度
 */
@property (nonatomic, assign) CGFloat topBannerHeight;

@end

@implementation CS_Page_QueryPanelView

-(CGFloat)layoutView:(UIView *)superView primaryY:(CGFloat)primaryY{
    
    self.frame = CGRectMake(0, 0, kWindowW, kWindowH);
    
    self.topBannerHeight = HEIGHT_NAVIGATIONBAR;
    
    [self addSubview:self.queryTopBackView];
    
    [self addSubview:self.queryConditionSwitchBackView];
    
    [self addSubview:self.backButton];
    
    if (!self.isSwithBarVisible) {
        [self.queryConditionSwitchBackView removeFromSuperview];
    }
    
    [self showSupportView];
    
    self.layer.opacity = 0.0;
    
    [superView addSubview:self];
    [UIView animateWithDuration:0.3 animations:^{
        self.layer.opacity = 1.0;
    }];
    
    return kWindowH;
    
}



#pragma mark --- 显示分类方式
/**
 * 显示辅助信息
 */
-(void)showSupportView{
    
    if (self.superview) {
        [self.superview addSubview:self];
    }
    
    if (self.moduleArray) {
        
        //条件过滤栏隐藏
        if (self.queryFilterPannelView) {
            [self.queryFilterPannelView.queryConditionPannelView removeFromSuperview];
            [self.queryFilterPannelView removeFromSuperview];
        }
        
        //新的查询界面，区分了查询模块
        [self.module_CS_Page_TabbarContainerView layoutView:self primaryY:self.topBannerHeight];
        
        for (int i = 0; i < self.moduleArray.count; i++) {
            
            CSQueryModuleModel *queryModuleModel = [self.moduleArray objectAtIndex:i];
            
            UIScrollView *scrollView = [self.module_CS_Page_TabbarContainerView getSuperPanelByTitle:queryModuleModel.queryModuleName];
            scrollView.tag = TAG_QUERY_INPUT_PANNEL_SCROLL_VIEW;
            scrollView.delegate = self;
            REMOVE_SUBVIEWS(scrollView);
            
            NSArray *queryConditions = queryModuleModel.queryModuleConditions;
            
            CGFloat primaryY = 0.0;
            
            //显示查询条件
            if (queryConditions != nil) {
                
            }
            
            self.queryInputTextField.placeholder = ((CSQueryModuleModel *)[self.moduleArray objectAtIndex:0]).modulePlaceHolder;
            
            [self.queryInputTextField becomeFirstResponder];
            
            if (self.customSuperViewDisplayHandler) {
                
                primaryY = self.customSuperViewDisplayHandler(queryModuleModel, primaryY, scrollView);
                
            }
            
            //显示历史记录
            UIView *historyView = [self getHistory:queryModuleModel.queryModuleName primaryY:primaryY superHeight:scrollView.frame.size.height];
            [scrollView addSubview:historyView];
            primaryY += historyView.frame.size.height;
            
            scrollView.contentSize = CGSizeMake(0, primaryY + 1);
            
        }
        
    }else{
        
        if (self.isSwithBarVisible) {
            [self addSubview:self.queryConditionSwitchBackView];
        }
        
        [self addSubview:self.expandQueryScrollView];
        
        //显示分类方式
        [self.expandQueryScrollView addSubview:self.categoryTypeBackgroundView];
        
        //显示历史记录
        [self.expandQueryScrollView addSubview:self.historyBackgroundView];
        
        self.expandQueryScrollView.contentSize = CGSizeMake(0, self.historyBackgroundView.frame.origin.y + self.historyBackgroundView.frame.size.height);
        
    }
    
}

/**
 * 获取对应模块的历史记录
 * @params moduleName 模块名称
 */
-(UIView *)getHistory:(NSString *)moduleName primaryY:(CGFloat)primaryY superHeight:(CGFloat)superHeight{
    
    UIView *historyBackgroundView = [UIView new];
    
    NSArray *queryHistorys = [self getQueryKeysWithModuleName:moduleName];
    
    CGFloat localPrimaryY = 0;
    
    //搜索历史标题
    CS_Page_SectionTitleView *page_SectionTitleView = [CS_Page_SectionTitleView page_SectionTitleView:@"搜索历史" color:COLOR_TEXT_1 image:nil];
    page_SectionTitleView.font = [UIFont boldSystemFontOfSize:14.0];
    page_SectionTitleView.isTopSeperatorLineHide= YES;
    localPrimaryY = [page_SectionTitleView layoutView:historyBackgroundView primaryY:localPrimaryY];
    
    WS(weakSelf);
    __block NSString *weakModuleName = moduleName;
    
    //搜索历史项
    for ( int i = 0; i < queryHistorys.count; i++) {
        
        QueryRecordModel *queryRecordModel = [queryHistorys objectAtIndex:queryHistorys.count - i - 1];
        
        CS_Item_QueryHistoryView *historyItemView = [CS_Item_QueryHistoryView item_QueryHistoryViewWithRecordModel:queryRecordModel selectClick:^(QueryRecordModel *queryRecordModel) {
            
            //步骤1：更新当前模块的查询参数
            CSQueryModuleModel *queryModuleModel = [self.moduleArray objectAtIndex:self.module_CS_Page_TabbarContainerView.currentIndex];
            NSArray *conditions = queryModuleModel.queryModuleConditions;
            BOOL isFirstQueryModel = YES;
            
            for (int j = 0; j < conditions.count; j++) {
                
                CSConditionModel *conditionModel = [conditions objectAtIndex:j];
                conditionModel.value = @"";
                
                for (int k = 0; k < queryRecordModel.params.count; k++) {
                    
                    QueryRecordParamModel *recordParamModel = [queryRecordModel.params objectAtIndex:k];
                    
                    if ([recordParamModel.param_name isEqualToString:KEY_HISTORY_INPUT_TEXT]
                        && isFirstQueryModel
                        && conditionModel.queryConditionDisplayMode == CSQueryConditionDisplayMode_InputText) {
                        
                        //更新输入栏
                        weakSelf.queryInputTextField.text = recordParamModel.param_value;
                        conditionModel.value = recordParamModel.param_value;
                        isFirstQueryModel = NO;
                        
                    }else if ([recordParamModel.param_name isEqualToString:conditionModel.placeHolder]) {
                        
                        //更新普通项
                        conditionModel.value = recordParamModel.param_value;
                        
                    }
                }
            }
            
            //步骤二：执行查询操作
            
            //将输入提示界面清除
            [self.module_CS_Page_TabbarContainerView removeFromSuperview];
            
            //布局查询结果界面
            CGFloat primaryY = self.topBannerHeight;
            primaryY = [self layoutQueryFilterPannelView:self primaryY:primaryY];
            
            //执行查询处理
            queryModuleModel.moduleQueryHandler(conditions, weakSelf.queryFilterPannelView.focusedContainerView);
            
            [self.queryInputTextField resignFirstResponder];
            
        } remove:^(QueryRecordModel *queryRecordModel) {
            
            [weakSelf.queryRecordManager deleteRecord:queryRecordModel];
            
            [weakSelf refreshHistoryView];
            
        }];
        
        localPrimaryY = [historyItemView layoutView:historyBackgroundView primaryY:localPrimaryY];
        
    }
    
    CGFloat needHeight = localPrimaryY + 50;
    
    if (primaryY + needHeight < superHeight) {
        needHeight = superHeight - primaryY;
    }
    
    historyBackgroundView.frame = CGRectMake(0, primaryY, kWindowW, needHeight);
    
    //添加清空按钮
    UIButton *clearHistoryButton = [UIButton new];
    clearHistoryButton.titleLabel.font = [UIFont systemFontOfSize:FONT_SIZE_1];
    [clearHistoryButton setTitle:@"清空搜索记录" forState:UIControlStateNormal];
    [clearHistoryButton setTitleColor:COLOR_THEME forState:UIControlStateNormal];
    [clearHistoryButton addTarget:self action:@selector(clearHistoryClick) forControlEvents:UIControlEventTouchUpInside];
    clearHistoryButton.frame = CGRectMake(0, historyBackgroundView.frame.size.height - 50, kWindowW, 40);
    [historyBackgroundView addSubview:clearHistoryButton];
    
    return historyBackgroundView;
}

-(void)refreshHistoryView{
    
    //更新历史记录视图
    UIScrollView *scrollView = [self.module_CS_Page_TabbarContainerView getSuperPanelByIndex:self.module_CS_Page_TabbarContainerView.currentIndex];
    CSQueryModuleModel *queryModuleModel = [self.moduleArray objectAtIndex:self.module_CS_Page_TabbarContainerView.currentIndex];
    scrollView.tag = TAG_QUERY_INPUT_PANNEL_SCROLL_VIEW;
    scrollView.delegate = self;
    REMOVE_SUBVIEWS(scrollView);
    CGFloat primaryY = 0.0;
    UIView *historyView = [self getHistory:queryModuleModel.queryModuleName primaryY:primaryY superHeight:scrollView.frame.size.height];
    [scrollView addSubview:historyView];
    primaryY += historyView.frame.size.height;
    scrollView.contentSize = CGSizeMake(0, primaryY + 1);
    
}

-(void)clearHistoryClick{
    
    CSQueryModuleModel *queryModuleModel = [self.moduleArray objectAtIndex:self.module_CS_Page_TabbarContainerView.currentIndex];
    [self.queryRecordManager clearRecords:queryModuleModel.queryModuleName];
    [self refreshHistoryView];
    
}

/**
 * 换茬查询视图
 */
-(CSBaseView *)getConditionViews:(CSConditionModel *)conditionModel{
    
    //输入类型
    if (conditionModel.type == CSViewType_PageTextFieldView) {
        
        CS_Page_TextFieldView *page_TextFieldView = [CS_Page_TextFieldView textFiledWithPlaceHolder:conditionModel.placeHolder keyboardType:UIKeyboardTypeDefault data:@""];
        return page_TextFieldView;
        
    }else if (conditionModel.type == CSViewType_PageTimePickView) {
        
        CS_Page_TextFieldView *page_TextFieldView = [CS_Page_TextFieldView textFiledWithPlaceHolder:conditionModel.placeHolder keyboardType:UIKeyboardTypeDefault data:@""];
        page_TextFieldView.textFieldType = CSTextFieldType_DateTime;
        return page_TextFieldView;
        
    }else if (conditionModel.type == CSViewType_PageTextSelectView) {
        
        CS_Page_TextSelectView *page_TextSelectView = [CS_Page_TextSelectView pageTextSelectView:conditionModel.placeHolder selectItems:conditionModel.selectItems ? conditionModel.selectItems : @[] textFieldType:0];
        return page_TextSelectView;
        
    }else if (conditionModel.type == CSViewType_PageRadioView) {
        
        CS_Query_RadioView *page_RadioView = [CS_Query_RadioView query_RadioView:conditionModel];
        return page_RadioView;
        
    }
    
    return nil;
}

-(void)hideSupportView{
    
    [self.queryConditionSwitchBackView removeFromSuperview];
    [self.expandQueryScrollView removeFromSuperview];
    self.frame = CGRectMake(0, 0, kWindowW, self.topBannerHeight);
    
}

-(UIView *)categoryTypeBackgroundView{
    if (_categoryTypeBackgroundView == nil) {
        _categoryTypeBackgroundView = [[UIView alloc] init];
        CGFloat primaryY = 0.0;
        
        for (int i = 0; i < self.conditionArray.count; i++) {
            
            CSConditionModel *conditionModel = [self.conditionArray objectAtIndex:i];
            
            //如果是可选择类型
            if (conditionModel.type == CSViewType_PageTextSelectView
                ||conditionModel.type == CSViewType_PageRadioView) {
                
                CS_Query_RadioView *queryRadioView = [CS_Query_RadioView query_RadioView:conditionModel];
                conditionModel.view = queryRadioView;
                primaryY = [queryRadioView layoutView:_categoryTypeBackgroundView primaryY:primaryY];
                
            }
            
        }
        
        _categoryTypeBackgroundView.frame = CGRectMake(0, 0, kWindowW, primaryY);
        _categoryTypeBackgroundView.backgroundColor = [UIColor whiteColor];
        
    }
    return _categoryTypeBackgroundView;
}

-(NSArray *)getQueryKeys{
    
    self.queryRecords = [self.queryRecordManager getRecords:self.vc_name];
    
    return self.queryRecords;
    
}

/**
 * 获取模块对应的查询记录
 */
-(NSArray *)getQueryKeysWithModuleName:(NSString *)moduleName{
    return [self.queryRecordManager getRecords:moduleName];
}

-(QueryRecordManager *)queryRecordManager{
    if (_queryRecordManager == nil) {
        _queryRecordManager = [QueryRecordManager new];
    }
    return _queryRecordManager;
}

#pragma mark --- UITextFieldDelegate

-(void)textFieldDidBeginEditing:(UITextField *)textField{
    textField.text = @"";
    [self showSupportView];
}

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    
    self.selectConditionModel.value = newString;
    
    return YES;
}

- (BOOL)textFieldShouldClear:(UITextField *)textField{
    self.selectConditionModel.value = @"";
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    if (self.moduleArray) {
        
        CSQueryModuleModel *queryModuleModel = [self.moduleArray objectAtIndex:self.module_CS_Page_TabbarContainerView.currentIndex];
        
        if (queryModuleModel.moduleQueryHandler) {
            
            [self.queryFilterPannelView clearContainerViews];
            [self.module_CS_Page_TabbarContainerView removeFromSuperview];
            
            CGFloat primaryY = self.topBannerHeight;
            
            primaryY = [self layoutQueryFilterPannelView:self primaryY:primaryY];
            
            //修改输入栏对应的关键字
            for (int i = 0; i < queryModuleModel.queryModuleConditions.count; i++) {
                
                CSConditionModel *conditionModel = [queryModuleModel.queryModuleConditions objectAtIndex:i];
                
                if (conditionModel.queryConditionDisplayMode == CSQueryConditionDisplayMode_InputText) {
                    conditionModel.isFocused = YES;
                    conditionModel.value = self.queryInputTextField.text;
                    break;
                }
            }
            
            
            queryModuleModel.moduleQueryHandler(queryModuleModel.queryModuleConditions, self.queryFilterPannelView.focusedContainerView);
            
            if (![self isNullOrEmpty:self.queryKeyString]
                &&![self.queryKeyString isEqualToString:self.queryInputTextField.text]) {
                
                for (int i = 0; i < queryModuleModel.queryModuleConditions.count; i++) {
                    CSConditionModel *conditionModel = [queryModuleModel.queryModuleConditions objectAtIndex:i];
                    if (conditionModel.queryConditionDisplayMode == CSQueryConditionDisplayMode_InputText) {
                        conditionModel.isRefreshRequired = YES;
                    }
                }
            }
            
            //保存当前模块的对应查询记录
            if (![self isNullOrEmpty:textField.text]) {
                [self saveQueryRecordWithModule:queryModuleModel];
            }
            
            /**
             * 对于搜索结果的变色处理
             * 需要在关闭后将这种变色处理消除掉
             */
            if (![self isNullOrEmpty:self.queryKeyString]) {
                //如果之前有对应的关键字，就先去掉
                [CSBaseView clearApplicationColoredKey:self.queryKeyString];
            }
            
            if (![self isNullOrEmpty:self.queryInputTextField.text]) {
                
                //重新设置输入关键字
                self.queryKeyString = self.queryInputTextField.text;
                
                //如果输入条件不为空
                [CSBaseView setApplicationColoredString:self.queryKeyString color:[UIColor colorFromHexCode:@"fe3116"]];
                
            }
            
        }
        
    }else if (self.doQueryClick) {
        
        [self updateOriginViewValue];
        
        self.doQueryClick(nil);
        
        if (![self isNullOrEmpty:textField.text]) {
            [self saveQueryRecord];
        }
        
        [self hideSupportView];
        
    }
    
    [textField resignFirstResponder];
    
    return YES;
}

-(CGFloat)layoutQueryFilterPannelView:(UIView *)superView primaryY:(CGFloat)primaryY{
    
    if (self.queryFilterPannelView) {
        [self.queryFilterPannelView removeFromSuperview];
        self.queryFilterPannelView = nil;
    }
    
    CGFloat lcoalPrimaryY = primaryY;
    
    CSQueryModuleModel *moduleModel = [self.moduleArray objectAtIndex:self.module_CS_Page_TabbarContainerView.currentIndex];
    
    self.queryFilterPannelView = [CS_Page_QueryFilterPannelView page_QueryFilterPannelViewWidthConditions:moduleModel.queryModuleConditions];
    
    WS(weakSelf);
    self.queryFilterPannelView.onConditionChangedHandler = ^{
        
        CSQueryModuleModel *queryModuleModel = [weakSelf.moduleArray objectAtIndex:weakSelf.module_CS_Page_TabbarContainerView.currentIndex];
        NSArray *conditionModels = queryModuleModel.queryModuleConditions;
        
        for (int i = 0; i < conditionModels.count; i++) {
            CSConditionModel *conditionModel = [conditionModels objectAtIndex:i];
            if (conditionModel.queryConditionDisplayMode == CSQueryConditionDisplayMode_InputText) {
                if (conditionModel.isFocused) {
                    conditionModel.value = weakSelf.queryInputTextField.text;
                }else{
                    conditionModel.value = @"";
                }
            }
        }
        
        moduleModel.moduleQueryHandler(moduleModel.queryModuleConditions, weakSelf.queryFilterPannelView.focusedContainerView);
    };
    
    lcoalPrimaryY = [self.queryFilterPannelView layoutView:self primaryY:lcoalPrimaryY];
    
    return lcoalPrimaryY;
    
}


-(void)saveQueryRecordWithModule:(CSQueryModuleModel *)queryModuleModel{
    
    QueryRecordModel *queryRecordModel = [QueryRecordModel new];
    queryRecordModel.vc_name = queryModuleModel.queryModuleName;
    queryRecordModel.params = [NSMutableArray new];
    
    QueryRecordParamModel *textParamModel = [QueryRecordParamModel new];
    textParamModel.record_type = [NSString stringWithFormat:@"%ld", CSQueryConditionDisplayMode_InputText];//对应的输入框类型
    textParamModel.param_name = KEY_HISTORY_INPUT_TEXT;
    textParamModel.param_value = self.queryInputTextField.text;
    
    [queryRecordModel.params addObject:textParamModel];
    
    for (int i = 0; i < self.conditionArray.count; i++) {
        
        CSConditionModel *conditionModel = [self.conditionArray objectAtIndex:i];
        QueryRecordParamModel *paramModel = [QueryRecordParamModel new];
        paramModel.record_type = [NSString stringWithFormat:@"%ld", conditionModel.queryConditionDisplayMode];
        paramModel.param_name = conditionModel.placeHolder;
        paramModel.param_value = conditionModel.value;
        paramModel.param_contentValue = conditionModel.contentValue;
        [queryRecordModel.params addObject:paramModel];
        
    }
    
    [self.queryRecordManager saveRecord:queryRecordModel];
    
    [self getQueryKeys];
    
    //记录总数大于指定数量，删去最早的一个
    if(self.queryRecords.count > 10){
        
        QueryRecordModel *firstQueryRecordModel = [self.queryRecords objectAtIndex:0];
        
        [self.queryRecordManager deleteRecord:firstQueryRecordModel];
        
    }
    
    [self refreshRecordView];
    
}

-(void)saveQueryRecord{
    
    QueryRecordModel *queryRecordModel = [QueryRecordModel new];
//    CSQueryModuleModel *queryModuleModel = [self.moduleArray objectAtIndex:self.module_CS_Page_TabbarContainerView.currentIndex];
//    queryRecordModel.vc_name = [NSString stringWithFormat:@"%@--%@", self.vc_name + queryModuleModel.queryModuleName];
    queryRecordModel.vc_name = self.vc_name;
    queryRecordModel.params = [NSMutableArray new];
    
    QueryRecordParamModel *textParamModel = [QueryRecordParamModel new];
    textParamModel.record_type = [NSString stringWithFormat:@"%ld", CSViewType_PageTextFieldView];
    textParamModel.param_name = self.focusModel.placeHolder;
    textParamModel.param_value = self.focusModel.value;
    
    [queryRecordModel.params addObject:textParamModel];
    
    for (int i = 0; i < self.conditionArray.count; i++) {
        
        CSConditionModel *conditionModel = [self.conditionArray objectAtIndex:i];
        
        //设置该次查询的参数
        if (conditionModel.type == CSViewType_PageTextSelectView && conditionModel == self.focusModel) {
            
            QueryRecordParamModel *paramModel = [QueryRecordParamModel new];
            paramModel.record_type = [NSString stringWithFormat:@"%ld", CSViewType_PageTextSelectView];
            paramModel.param_name = conditionModel.placeHolder;
            paramModel.param_value = conditionModel.value;
            [queryRecordModel.params addObject:paramModel];
            
        }else if (conditionModel.type == CSViewType_PageRadioView
                  || conditionModel.type == CSViewType_PageTextSelectView) {
            
            QueryRecordParamModel *paramModel = [QueryRecordParamModel new];
            paramModel.record_type = [NSString stringWithFormat:@"%ld", CSViewType_PageRadioView];
            paramModel.param_name = conditionModel.placeHolder;
            paramModel.param_value = conditionModel.value;
            [queryRecordModel.params addObject:paramModel];
            
        }
    }
    
    [self.queryRecordManager saveRecord:queryRecordModel];
    
    [self getQueryKeys];
    
    //记录总数大于指定数量，删去最早的一个
    if(self.queryRecords.count > 10){
        
        QueryRecordModel *firstQueryRecordModel = [self.queryRecords objectAtIndex:0];
        
        [self.queryRecordManager deleteRecord:firstQueryRecordModel];
        
    }
    
    [self refreshRecordView];
    
}

-(void)textFieldDidEndEditing:(UITextField *)textField{
    
    //    if (![self isNullOrEmpty:textField.text]
    //        && self.doQueryClick) {
    //
    //        [self updateOriginViewValue];
    //
    //        self.doQueryClick(nil);
    //
    //        [self.queryConditionSwitchBackView removeFromSuperview];
    //        [self.expandQueryScrollView removeFromSuperview];
    //
    //    }
    
}

-(void)updateOriginViewValue{
    
    for (int i = 0; i < self.conditionArray.count; i++) {
        
        CSConditionModel *conditionModel = [self.conditionArray objectAtIndex:i];
        if(conditionModel.originView){
            
            if (conditionModel.type == CSViewType_PageTextFieldView) {
                
                if (conditionModel == self.focusModel) {
                    conditionModel.originView.value = [self checkString:self.queryInputTextField.text];
                }else{
                    conditionModel.originView.value = @"";
                }
                
            }else if (conditionModel.type == CSViewType_PageTextSelectView
                      || conditionModel.type == CSViewType_PageRadioView){
                
                conditionModel.originView.value = conditionModel.value;
                
            }
        }
        
    }
    
}

/**
 *  将null替换为@""
 *
 *  @param stringValue 要处理的字符串
 *
 *  @return 处理后的字符串
 */
-(NSString *)checkString:(NSString *)checkString{
    if (checkString == nil) {
        return @"";
    }
    return checkString;
}

/**
 * 更新查询区域
 */
-(void)updateQueryArea{
    return;
    
    REMOVE_SUBVIEWS(self.queryConditionBackView);
    
    [self.queryConditionBackView addSubview:self.queryTitleLabel];
    [self.queryConditionBackView addSubview:self.seperateLine];
    
    CGFloat resetWidth = MARGIN;
    CGFloat primaryY = 35.0;
    CGFloat cellHeight = 20.0;
    UILabel *lastLabel = nil;
    for (int i = 0; i < self.conditionArray.count; i++) {
        
        CSConditionModel *model = [self.conditionArray objectAtIndex:i];
        
        if ([self isNullOrEmpty:model.value] && model != self.focusModel) {
            continue;
        }
        
        UIButton *button = [UIButton new];
        button.layer.borderColor = COLOR_THEME.CGColor;
        button.backgroundColor = [UIColor clearColor];
        button.layer.borderWidth = 1.0;
        button.layer.cornerRadius = 2.0;
        button.layer.masksToBounds = YES;
        
        //适配按钮的大小
        
        NSString *condition = [NSString stringWithFormat:@"%@：%@", model.name, [self isNullOrEmpty:model.value]?@"":model.value];
        [button setTitle:condition forState:UIControlStateNormal];
        [button setTitleColor:COLOR_TEXT_2 forState:UIControlStateNormal];
        button.tag = i;
        button.titleLabel.font = [UIFont boldSystemFontOfSize:15.0];
        [button addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
        [button sizeToFit];
        button.frame = CGRectMake(button.frame.origin.x - 5, button.frame.origin.y - 5, button.frame.size.width + 10, button.frame.size.height + 10);
        CGFloat needWidth = button.frame.size.width;
        
        //如果查询条件为当前正在编辑条件
        if (model == self.focusModel) {
            button.layer.borderColor = [UIColor colorFromHexCode:@"#ffa007"].CGColor;
        }
        
        //如果超出，则换行
        if (resetWidth == resetWidth
            && needWidth + MARGIN + 10> kWindowW - 2 * MARGIN) {
            
        }else if (kWindowW - 2 * MARGIN < resetWidth + needWidth + MARGIN + 10) {
            primaryY += (10 + cellHeight);
            resetWidth = MARGIN;
        }
        button.frame = CGRectMake(MARGIN + resetWidth, primaryY, needWidth, 20);
        resetWidth += (needWidth + MARGIN);
        
        UILabel *plusLabel = [UILabel new];
        plusLabel.textColor = [UIColor colorFromHexCode:@"#999999"];
        plusLabel.text = @"+";
        plusLabel.frame = CGRectMake(MARGIN + resetWidth, primaryY, 10, 20);
        lastLabel = plusLabel;
        resetWidth += (10 + MARGIN);
        [self.queryConditionBackView addSubview:plusLabel];
        [self.queryConditionBackView addSubview:button];
    }
    
    if (lastLabel) {
        [lastLabel removeFromSuperview];
    }
    
    primaryY += (20 + 2 * MARGIN);
    
    if (primaryY > QUERY_AREA_HEIGHT - 10) {
        self.heightConditionArea = primaryY;
        self.queryConditionBackView.frame = CGRectMake(0, self.topBannerHeight + 30, kWindowW, self.heightConditionArea);
        self.seperateLine.frame = CGRectMake(0, primaryY - 10, kWindowW, 10);
        self.queryHistoryBackView.frame = CGRectMake(0, self.topBannerHeight + 30 + self.heightConditionArea, kWindowW, kWindowH - 30 - self.topBannerHeight - self.heightConditionArea);
    }
    
}

-(void)click:(id)sender{
    
    if ([sender isKindOfClass:[UIButton class]]) {
        
        UIButton *button = (UIButton *)sender;
        NSInteger index = button.tag;
        CSConditionModel *model = [self.conditionArray objectAtIndex:index];
        
        self.focusModel = model;
        
        [self scrollToConditionModel:model];
    }
    
}

/**
 * 滚动到指定模型对象
 */
-(void)scrollToConditionModel:(CSConditionModel *)model{
    UIView *view = model.view;
    [self.scrollView setContentOffset:CGPointMake(view.frame.size.width / 2.0 + view.frame.origin.x - self.focusDeviation, 0) animated:YES];
}

#pragma mark --- UIScrollViewDelegate
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    if (scrollView.tag == TAG_QUERY_INPUT_PANNEL_SCROLL_VIEW) {
        [self.queryInputTextField resignFirstResponder];
        return;
    }
    
    if (self.expandQueryScrollView == scrollView) {
        [self.queryInputTextField resignFirstResponder];
        return;
    }
    
    //偏移点
    CGFloat contentOffsetX = scrollView.contentOffset.x;
    
    //目标点
    CGFloat targetPointX = self.focusDeviation;
    
    CGFloat minDevation = CGFLOAT_MAX;
    int minDevationIndex = 0;
    
    for (int i = 0; i < self.conditionArray.count; i++) {
        
        CSConditionModel *model = [self.conditionArray objectAtIndex:i];
        
        if (model.type == CSViewType_PageRadioView
            ||model.type == CSViewType_PageTextSelectView) {
            continue;
        }
        
        UIView *view = model.view;
        CGFloat deviationValue = view.center.x - contentOffsetX - targetPointX;
        deviationValue = fabsf(deviationValue);
        
        if (deviationValue < minDevation) {
            minDevation = deviationValue;
            minDevationIndex = i;
        }
        
        CGFloat scale = 1.0;
        if (deviationValue < WIDTH_LEFT_KEY) {
            scale = (WIDTH_LEFT_KEY - deviationValue) / WIDTH_LEFT_KEY * 0.25 + 1.0;
        }
        view.transform = CGAffineTransformMakeScale(scale, scale);
        
    }
    
    //设置选中项
    CSConditionModel *model = [self.conditionArray objectAtIndex:minDevationIndex];
    self.queryInputTextField.placeholder = model.placeHolder;
    self.queryInputTextField.text = model.value;
    self.selectConditionModel = model;
    
    [self updateQueryArea];
    
   
    
}

-(void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
    
    
    
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    self.focusModel = self.selectConditionModel;
    
    [self updateQueryArea];
    
}

-(void)navigationBackClick{
    
    if (self.navigationBackHandler) {
        self.navigationBackHandler();
    }
    
}

-(void)cancelClick{
    WS(weakSelf);
    
    if (weakSelf.cancelClickHandler) {
        weakSelf.cancelClickHandler();
        return;
    }
    
    [UIView animateWithDuration:0.3 animations:^{
        weakSelf.layer.opacity = 0.0;
    } completion:^(BOOL finished) {
        [weakSelf removeFromSuperview];
        weakSelf.layer.opacity = 1.0;
        
        
    }];
}

-(void)clearHistory{
    
    [self.queryRecordManager clearRecords:self.vc_name];
    [self refreshRecordView];
    
}

#pragma mark --- lazy loading

#define WIDTH_BACK_IMAGE 20
#define MARGIN_BACK_IMAGE (WIDTH_BACK_IMAGE + 5)

-(CGFloat)backImageWidth{
    
    return MARGIN_BACK_IMAGE + 30;
    
//    if (self.navigationBackHandler) {
//        return WIDTH_BACK_IMAGE;
//    }else{
//        return 0;
//    }
    
}

-(CGFloat)backImageMargin{
    
    return MARGIN_BACK_IMAGE + 30;
    
//    if (self.navigationBackHandler) {
//        return MARGIN_BACK_IMAGE;
//    }else{
//        return 0;
//    }
    
}

-(void)doSearch{
    [self textFieldShouldReturn:self.queryInputTextField];
}

-(UIView *)queryTopBackView{
    if (_queryTopBackView == nil) {
        _queryTopBackView = [[UIView alloc] init];
        _queryTopBackView.backgroundColor = COLOR_THEME;
        
        if (![self isNullOrEmpty:self.title]) {
            
            CGFloat moreHeight = 52;//ong
            CGFloat moreMargin = 34;
            CGFloat queryDeviationHeight = 50;
            
            self.topBannerHeight = HEIGHT_NAVIGATIONBAR + moreHeight;
            
            self.titlLabel.text = self.title;
            self.titlLabel.frame = CGRectMake(MARGIN + [self backImageMargin], HEIGHT_STATUSBAR + 5, kWindowW - WIDTH_RIGHT_BUTTON - 3.0 * MARGIN + 1 - [self backImageWidth], 30);
            [_queryTopBackView addSubview:self.titlLabel];
            
            UIButton *searchButton = [[UIButton alloc] init];
            [searchButton setTitle:@"搜索" forState:UIControlStateNormal];
//            [searchButton setBackgroundImage:[CSPageEngine getImageWithKey:KEY_ICON_QUERY] forState:UIControlStateNormal];
            [searchButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            searchButton.titleLabel.font = [UIFont boldSystemFontOfSize:FONT_SIZE_1];
            [searchButton addTarget:self action:@selector(doSearch) forControlEvents:UIControlEventTouchUpInside];
            
            self.inputBackgroundView.frame = CGRectMake(CELL_EDIT_RIGHT_MARGIN, HEIGHT_STATUSBAR + 5 + queryDeviationHeight, kWindowW - CELL_EDIT_RIGHT_MARGIN - CELL_EDIT_RIGHT_MARGIN - moreMargin, 30);
            self.queryInputTextField.frame = CGRectMake(CELL_EDIT_RIGHT_MARGIN + 22 + 0.8 * MARGIN, HEIGHT_STATUSBAR + 5 + queryDeviationHeight, kWindowW - CELL_EDIT_RIGHT_MARGIN - CELL_EDIT_RIGHT_MARGIN - 32 - moreMargin, 30);
            self.queryIconImageView.frame = CGRectMake(CELL_EDIT_RIGHT_MARGIN + 5 + 5, HEIGHT_STATUSBAR + 5 + 5 + 3 + queryDeviationHeight, 14, 14);
//            searchButton.frame = CGRectMake(self.inputBackgroundView.frame.origin.x + self.inputBackgroundView.frame.size.width + 10, self.inputBackgroundView.frame.origin.y + 5, 20, 20);
            searchButton.frame = CGRectMake(self.inputBackgroundView.frame.origin.x + self.inputBackgroundView.frame.size.width, self.inputBackgroundView.frame.origin.y, 50, self.inputBackgroundView.frame.size.height);
            [_queryTopBackView addSubview:searchButton];
            
        }
        _queryTopBackView.frame = CGRectMake(0, 0, kWindowW, self.topBannerHeight);
        
        
        //右侧栏
        [_queryTopBackView addSubview:self.inputBackgroundView];
        [_queryTopBackView addSubview:self.queryInputTextField];
        [_queryTopBackView addSubview:self.queryIconImageView];
        
        //右侧侧按钮
        if (self.queryRightButton) {
            [_queryTopBackView addSubview:self.queryRightButton];
        }
        
        //查询左侧栏
        [_queryTopBackView addSubview:self.queryLeftButton];
        [_queryTopBackView addSubview:self.backButton];
        
        
    }
    
    return _queryTopBackView;
}

-(UITextField *)queryInputTextField{
    
    if (_queryInputTextField == nil) {
        _queryInputTextField = [[UITextField alloc] init];
        _queryInputTextField.placeholder = @"请输入关键词";
        _queryInputTextField.keyboardType = UIKeyboardTypeWebSearch;
        //        _queryInputTextField.frame = CGRectMake(self.queryLeftButton.frame.origin.x + self.queryLeftButton.frame.size.width + 1  + MARGIN, 25, kWindowW - 4 *MARGIN - WIDTH_LEFT_KEY - WIDTH_RIGHT_BUTTON, 30);
        
        if (self.queryRightButton) {
            _queryInputTextField.frame = CGRectMake(MARGIN * 1.8 + 22 + [self backImageMargin], HEIGHT_STATUSBAR + 5, kWindowW - 4.0 * MARGIN - WIDTH_RIGHT_BUTTON - 22 - [self backImageMargin], 30);
        }else{
            _queryInputTextField.frame = CGRectMake(MARGIN * 1.8 + 22 + [self backImageMargin], HEIGHT_STATUSBAR + 5, kWindowW - 3.0 * MARGIN - 22 - [self backImageMargin], 30);
        }
        
        _queryInputTextField.borderStyle = UITextBorderStyleNone;
        _queryInputTextField.font = [UIFont systemFontOfSize:15.0];
        _queryInputTextField.inputAccessoryView = [UIView new];
        _queryInputTextField.backgroundColor = [UIColor clearColor];
        _queryInputTextField.clearButtonMode = UITextFieldViewModeAlways;
        _queryInputTextField.delegate = self;
        
    }
    return _queryInputTextField;
}

-(UIButton *)queryLeftButton{
    
    if (_queryLeftButton == nil) {
        _queryLeftButton = [[UIButton alloc]init];
        _queryLeftButton.frame = CGRectMake(MARGIN, HEIGHT_STATUSBAR + 10, WIDTH_LEFT_KEY, 20);
        [_queryLeftButton setTitle:@"返回" forState:UIControlStateNormal];
        _queryLeftButton.titleLabel.textColor = COLOR_WHITE;
        [_queryLeftButton setTitleColor:COLOR_WHITE forState:UIControlStateNormal];
        _queryLeftButton.titleLabel.font = [UIFont systemFontOfSize:15.0];
        [_queryLeftButton addTarget:self action:@selector(navigationBackClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _queryLeftButton;
    
}

//-(UIButton *)queryRightButton{
//    if (_queryRightButton == nil) {
//        _queryRightButton = [[UIButton alloc]init];
//        [_queryRightButton setTitle:@"取消" forState:UIControlStateNormal];
//        [_queryRightButton addTarget:self action:@selector(cancelClick) forControlEvents:UIControlEventTouchUpInside];
//        _queryRightButton.titleLabel.textColor = [UIColor whiteColor];
//        _queryRightButton.titleLabel.font = [UIFont systemFontOfSize:15.0];
//        //        [_queryRightButton setImage:[UIImage imageNamed:@"query"] forState:UIControlStateNormal];
//        _queryRightButton.frame = CGRectMake(kWindowW - MARGIN - WIDTH_RIGHT_BUTTON, 30, WIDTH_RIGHT_BUTTON, 20);
//    }
//    return _queryRightButton;
//}

-(void)setRightButton:(UIButton *)queryRightButton{
    
    _queryRightButton = queryRightButton;
    
    if (_queryRightButton) {
        _queryRightButton.titleLabel.textColor = [UIColor whiteColor];
        _queryRightButton.titleLabel.font = [UIFont systemFontOfSize:15.0];
        if (_queryRightButton.currentBackgroundImage) {
            _queryRightButton.frame = CGRectMake(kWindowW - MARGIN - 25, HEIGHT_STATUSBAR + 10, 20, 20);
        }else{
            _queryRightButton.frame = CGRectMake(kWindowW - MARGIN - WIDTH_RIGHT_BUTTON, HEIGHT_STATUSBAR + 10, WIDTH_RIGHT_BUTTON, 20);
        }
        
    }
    
}

-(UIButton *)rightButton{
    return _queryRightButton;
}

-(UIButton *)backButton{
    
    if (_backButton == nil) {
        _backButton = [[UIButton alloc] init];
        [_backButton setImage:[CSPageEngine getImageWithKey:KEY_ICON_NAVIGATION_BACK] forState:UIControlStateNormal];
        [_backButton addTarget:self action:@selector(navigationBackClick) forControlEvents:UIControlEventTouchUpInside];
        _backButton.frame = CGRectMake(MARGIN - 2, HEIGHT_STATUSBAR + 5 + (30 - WIDTH_BACK_IMAGE)/2.0, WIDTH_BACK_IMAGE, WIDTH_BACK_IMAGE);
    }
    return _backButton;
    
}

-(UILabel *)titlLabel{
    
    if (_titlLabel == nil) {
        _titlLabel = [UILabel new];
        _titlLabel.textColor = [UIColor whiteColor];
        _titlLabel.textAlignment = NSTextAlignmentCenter;
        _titlLabel.font = [UIFont boldSystemFontOfSize:16.0];
        
    }
    return _titlLabel;
    
}

-(UIView *)inputBackgroundView{
    if (_inputBackgroundView == nil) {
        _inputBackgroundView = [[UIView alloc]init];
        _inputBackgroundView.backgroundColor = [UIColor whiteColor];
        _inputBackgroundView.layer.cornerRadius = 15;
        _inputBackgroundView.layer.masksToBounds = YES;
        if (self.queryRightButton) {
            _inputBackgroundView.frame = CGRectMake(MARGIN + [self backImageMargin], HEIGHT_STATUSBAR + 5, kWindowW - WIDTH_RIGHT_BUTTON - 3.0 * MARGIN + 1 - [self backImageWidth], 30);
        }else{
            _inputBackgroundView.frame = CGRectMake(MARGIN + [self backImageMargin], HEIGHT_STATUSBAR + 5, kWindowW - 2.0 * MARGIN + 1 - [self backImageWidth], 30);
        }
    }
    return _inputBackgroundView;
}

-(UIView *)queryConditionSwitchBackView{
    if (_queryConditionSwitchBackView == nil) {
        _queryConditionSwitchBackView = [[UIView alloc]init];
        _queryConditionSwitchBackView.backgroundColor = COLOR_THEME;
        _queryConditionSwitchBackView.frame = CGRectMake(0, self.topBannerHeight, kWindowW, 30);
        
        self.scrollView = [UIScrollView new];
        self.scrollView.frame = CGRectMake(MARGIN, 0, kWindowW - WIDTH_RIGHT_BUTTON - 3.0 * MARGIN + 1, 20);
        self.scrollView.showsHorizontalScrollIndicator = NO;
        self.scrollView.showsVerticalScrollIndicator = NO;
        self.scrollView.delegate = self;
        [_queryConditionSwitchBackView addSubview:self.scrollView];
        
        CGFloat primaryX = self.scrollView.frame.size.width / 2.0;
        
        int number = 0;
        
        for (int i = 0 ; i < self.conditionArray.count; i++) {
            
            CSConditionModel *queryModel = [self.conditionArray objectAtIndex:i];
            
            if (queryModel.type == CSViewType_PageRadioView
                ||queryModel.type == CSViewType_PageTextSelectView
                ) {
                continue;
            }
            
            UIButton *button = [UIButton new];
            [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            button.titleLabel.font = [UIFont systemFontOfSize:15.0];
            button.tag = i;
            
            CGFloat needWidth = [self estimateWith:queryModel.name font:button.titleLabel.font height:20];
            button.frame = CGRectMake(primaryX, 0, needWidth, 20);
            [button setTitle:queryModel.name forState:UIControlStateNormal];
            queryModel.view = button;
            [self.scrollView addSubview:button];
            
            [button addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
            
            primaryX += needWidth + 1.5 * MARGIN;
            primaryX += (1 + 1.5 * MARGIN);
            
            number++;
            
            if (self.focusModel == nil) {
                self.focusModel = queryModel;
            }
            
        }
        
        if (number >= 2) {
            self.isSwithBarVisible = YES;
        }
        
        self.scrollView.contentSize = CGSizeMake(primaryX + self.scrollView.frame.size.width / 2.0, 0);
        
        self.focusDeviation = self.scrollView.frame.size.width / 2.0;
        
        [self click:self.focusModel.view];
        
    }
    
    return _queryConditionSwitchBackView;
}

-(UIView *)queryConditionBackView{
    if (_queryConditionBackView == nil) {
        
        _queryConditionBackView = [UIView new];
        _queryConditionBackView.frame = CGRectMake(0, self.topBannerHeight + 30, kWindowW, QUERY_AREA_HEIGHT);
        self.heightConditionArea = QUERY_AREA_HEIGHT;
        
        [_queryConditionBackView addSubview:self.queryTitleLabel];
        
        self.seperateLine = [UIView new];
        self.seperateLine.backgroundColor = [UIColor colorFromHexCode:@"#e7e7e7"];
        self.seperateLine.frame = CGRectMake(0, QUERY_AREA_HEIGHT - 10, kWindowW, 10);
        [_queryConditionBackView addSubview:self.seperateLine];
        
    }
    return _queryConditionBackView;
}

-(UIView *)queryHistoryBackView{
    if (_queryHistoryBackView == nil) {
        
        _queryHistoryBackView = [UIView new];
        _queryHistoryBackView.frame = CGRectMake(0, self.topBannerHeight + 30 + self.heightConditionArea + 10, kWindowW, kWindowH - self.topBannerHeight + 30 + self.heightConditionArea);
        
        
    }
    return _queryHistoryBackView;
}

-(UILabel *)queryTitleLabel{
    if (_queryTitleLabel == nil) {
        _queryTitleLabel = [UILabel new];
        _queryTitleLabel.textColor = COLOR_THEME;
        _queryTitleLabel.text = @"搜索条件";
        _queryTitleLabel.font = [UIFont boldSystemFontOfSize:14.0];
        _queryTitleLabel.frame = CGRectMake(10, 10, 100, 15);
    }
    return _queryTitleLabel;
}

-(UIView *)switchLine{
    if (_switchLine == nil) {
        _switchLine = [UIView new];
        _switchLine.backgroundColor = [UIColor whiteColor];
    }
    return _switchLine;
}

-(UIImageView *)queryIconImageView{
    if (_queryIconImageView == nil) {
        _queryIconImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"tab_cx"]];
        _queryIconImageView.frame = CGRectMake(MARGIN + 5 + 3 + [self backImageMargin], HEIGHT_STATUSBAR + 5 + 5 + 3, 14, 14);
    }
    return _queryIconImageView;
}

-(CS_Page_SectionTitleView *)categoryType_CS_Page_SectionTitleView{
    if (_categoryType_CS_Page_SectionTitleView == nil) {
        _categoryType_CS_Page_SectionTitleView = [CS_Page_SectionTitleView page_SectionTitleView:@"分类方式" color:COLOR_TEXT_2 image:nil];
        _categoryType_CS_Page_SectionTitleView.isTopSeperatorLineHide = YES;
    }
    return _categoryType_CS_Page_SectionTitleView;
}

-(NSMutableArray *)categoryButtonArray{
    if (_categoryButtonArray == nil) {
        _categoryButtonArray = [NSMutableArray new];
    }
    return _categoryButtonArray;
}

-(CS_Page_SectionTitleView *)history_CS_Page_SectionTitleView{
    if (_history_CS_Page_SectionTitleView == nil) {
        _history_CS_Page_SectionTitleView = [CS_Page_SectionTitleView page_SectionTitleView:@"搜索历史" color:COLOR_TEXT_1 image:nil];
        _history_CS_Page_SectionTitleView.isTopSeperatorLineHide = NO;
    }
    return _history_CS_Page_SectionTitleView;
}

-(UIView *)historyBackgroundView{
    if (_historyBackgroundView == nil) {
        _historyBackgroundView = [[UIView alloc] init];
        _historyBackgroundView.backgroundColor = [UIColor whiteColor];
        [self refreshRecordView];
    }
    return _historyBackgroundView;
}

/**
 * 刷新搜索记录视图
 */
-(void)refreshRecordView{
    
    CGFloat primaryY = self.categoryTypeBackgroundView.frame.origin.y + self.categoryTypeBackgroundView.frame.size.height;
    
    //添加历史标题
    CGFloat localPrimaryY = 0.0;
    localPrimaryY = [self.history_CS_Page_SectionTitleView layoutView:_historyBackgroundView primaryY:localPrimaryY];
    
    //历史记录滚动条
    [_historyBackgroundView addSubview:self.historyScrollView];
    
    REMOVE_SUBVIEWS(self.historyScrollView);
    
    //历史记录项
    CGFloat scrollPrimaryY = 0.0;
    NSArray *queryKeys = [self getQueryKeys];
    WS(weakSelf);
    
    if (queryKeys.count > 0) {
        
        for (int i = 1; i <= queryKeys.count; i++) {
            
            QueryRecordModel *queryRecordModel = [queryKeys objectAtIndex:queryKeys.count - i];
            
            CS_Item_QueryHistoryView *itemView = [CS_Item_QueryHistoryView item_QueryHistoryViewWithRecordModel:queryRecordModel selectClick:^(QueryRecordModel *queryRecordModel) {
                
                //更新参数
                for (int j = 0; j < weakSelf.conditionArray.count; j++) {
                    
                    CSConditionModel *conditionModel = (CSConditionModel *)[weakSelf.conditionArray objectAtIndex:j];
                    conditionModel.value = @"";
                    
                    for (int k = 0; k < queryRecordModel.params.count; k++) {
                        
                        QueryRecordParamModel *recordParamModel = [queryRecordModel.params objectAtIndex:k];
                        
                        if ([recordParamModel.param_name isEqualToString:conditionModel.placeHolder]) {
                            
                            conditionModel.value = recordParamModel.param_value;
                            
                            //如果是输入框类型，则设置为focusModel
                            if ([recordParamModel.record_type integerValue] == CSViewType_PageTextFieldView) {
                                
                                weakSelf.focusModel = conditionModel;
                                weakSelf.queryInputTextField.text = recordParamModel.param_value;
                                
                            }else if ([recordParamModel.record_type integerValue] == CSViewType_PageRadioView
                                      || [recordParamModel.record_type integerValue] == CSViewType_PageTextSelectView){
                                
                                if ([conditionModel.view isKindOfClass:[CS_Query_RadioView class]]) {
                                    
                                    [((CS_Query_RadioView *)conditionModel.view) select:recordParamModel.param_value];
                                    
                                }
                                
                            }
                            
                            continue;
                            
                        }
                        
                    }
                    
                }
                
                //更新对应界面原始视图的参数
                [weakSelf updateOriginViewValue];
                
                //执行查询操作
                weakSelf.doQueryClick(nil);
                
                [weakSelf hideSupportView];
                
                [weakSelf.queryInputTextField resignFirstResponder];
                
            } remove:^(QueryRecordModel *queryRecordModel) {
                
                [weakSelf.queryRecordManager deleteRecord:queryRecordModel];
                
                [weakSelf refreshRecordView];
                
            }];
            
            scrollPrimaryY = [itemView layoutView:self.historyScrollView primaryY:scrollPrimaryY];
        }
    }
    
    
    self.historyScrollView.contentSize = CGSizeMake(0, scrollPrimaryY);
    self.historyScrollView.frame = CGRectMake(0, localPrimaryY, kWindowW, scrollPrimaryY);
    
    CGFloat needHeight = localPrimaryY + scrollPrimaryY + 50;
    
    if (primaryY + needHeight < self.expandQueryScrollView.frame.size.height) {
        needHeight = self.expandQueryScrollView.frame.size.height - primaryY + 1;
    }
    
    _historyBackgroundView.frame = CGRectMake(0, primaryY, kWindowW, needHeight);
    
    //添加清空按钮
    self.clearHistoryButton.frame = CGRectMake(0, _historyBackgroundView.frame.size.height - 50, kWindowW, 40);
    [_historyBackgroundView addSubview:self.clearHistoryButton];
    
    self.expandQueryScrollView.contentSize = CGSizeMake(0, primaryY + needHeight);
    
}

-(UIButton *)clearHistoryButton{
    if (_clearHistoryButton == nil) {
        _clearHistoryButton = [[UIButton alloc]init];
        _clearHistoryButton.titleLabel.font = [UIFont systemFontOfSize:15.0];
        [_clearHistoryButton setTitle:@"清空搜索记录" forState:UIControlStateNormal];
        [_clearHistoryButton setTitleColor:COLOR_THEME forState:UIControlStateNormal];
        [_clearHistoryButton addTarget:self action:@selector(clearHistory) forControlEvents:UIControlEventTouchUpInside];
    }
    return _clearHistoryButton;
}

-(UIScrollView *)historyScrollView{
    if (_historyScrollView == nil) {
        _historyScrollView = [UIScrollView new];
    }
    return _historyScrollView;
}

-(UIScrollView *)expandQueryScrollView{
    if (_expandQueryScrollView == nil) {
        _expandQueryScrollView = [UIScrollView new];
        _expandQueryScrollView.frame = CGRectMake(0, self.topBannerHeight + 30, kWindowW, kWindowH - self.topBannerHeight - 30);
        if (!self.isSwithBarVisible) {
            _expandQueryScrollView.frame = CGRectMake(0, self.topBannerHeight, kWindowW, kWindowH - self.topBannerHeight);
        }
        _expandQueryScrollView.backgroundColor = [UIColor whiteColor];
        _expandQueryScrollView.delegate = self;
    }
    return _expandQueryScrollView;
}

-(CS_Page_TabbarContainerView *)module_CS_Page_TabbarContainerView{
    
    if (_module_CS_Page_TabbarContainerView == nil) {
        
        NSMutableArray *moduleNames = [NSMutableArray new];
        
        for (int i = 0; i < self.moduleArray.count; i++) {
            
            CSQueryModuleModel *queryModel = [self.moduleArray objectAtIndex:i];
            [moduleNames addObject:queryModel.queryModuleName];
            
        }
        WS(weakSelf);
        _module_CS_Page_TabbarContainerView = [CS_Page_TabbarContainerView page_TabbarContainerView:moduleNames needHeight:(kWindowH - self.topBannerHeight) onTabIndexChangedHandler:^(NSInteger currentIndex, NSString *currentTitle) {
            
            CSQueryModuleModel *queryModuleModel = [self.moduleArray objectAtIndex:currentIndex];
            weakSelf.queryInputTextField.placeholder = queryModuleModel.modulePlaceHolder;
            
        }];
        _module_CS_Page_TabbarContainerView.tabBackgroundColor = COLOR_THEME;
        _module_CS_Page_TabbarContainerView.textColor = [UIColor whiteColor];
        _module_CS_Page_TabbarContainerView.tablineColor = COLOR_WHITE;
    }
    return _module_CS_Page_TabbarContainerView;
}

//-(UIView *)queryResultDisplayPannelView{
//
//    if (_queryResultDisplayPannelView == nil) {
//        _queryResultDisplayPannelView = [[UIView alloc] init];
//        _queryResultDisplayPannelView.frame = CGRectMake(0, HEIGHT_NAVIGATIONBAR, kWindowW, kWindowH - HEIGHT_NAVIGATIONBAR);
//        _queryResultDisplayPannelView.backgroundColor = COLOR_PAGE_BACKGROUND;
//    }
//    return _queryResultDisplayPannelView;
//
//}

@end
